//
//  ViewController.swift
//  demo
//
//  Created by 王文东 on 2024/12/31.
//

import UIKit
import Flutter

class ViewController: UIViewController {
    private var flutterViewController: FlutterViewController!
    private var methodChannel: FlutterMethodChannel!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
        flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
        methodChannel = FlutterMethodChannel(name: "com.sunricher.dancing_with_flutter/channel", binaryMessenger: flutterViewController.binaryMessenger)
        
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.addTarget(self, action: #selector(showFlutter), for: .touchUpInside)
        button.setTitle("Show Flutter!", for: UIControl.State.normal)
        button.frame = CGRect(x: 80, y: 210, width: 160, height: 40)
        button.backgroundColor = UIColor.magenta
        self.view.addSubview(button)
    }

    @objc func showFlutter() {
        /*
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4)) {
            self.sendDataToFlutter()
            NSLog("sent data to flutter", "")
        }
         */
        present(flutterViewController, animated: true)
    }
    
    @objc func sendDataToFlutter() {
        let data = ["name": "John", "age": 30] as [String: Any]
        methodChannel.invokeMethod("sendDataToFlutter", arguments: data) { result in
            if let error = result as? FlutterError {
                NSLog("Error: \(error.message ?? "Unknown error")", "")
            } else if let response = result as? String {
                NSLog("Response from Flutter: \(response)", "")
            }
        }
    }

}

